﻿using FC.Utils;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace FC.Weather.PM25
{
    /// <summary>
    /// 
    /// </summary>
    public class PM25inWeather
    {
        /// <summary>
        /// 获取PM2.5指数
        /// </summary>
        /// <param name="city"></param>
        /// <returns></returns>
        public PM2_5 GetPM2_5(string city)
        {
            string url = $"http://www.pm25.in/api/querys/pm2_5.json?city={city}&token={"5j1znBVAsnSf5xQyNQyq"}&stations=no";
            try
            {
                Uri httpURL = new Uri(url);
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
                Stream respStream = httpResp.GetResponseStream();
                StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
                string jsonContent = respStreamReader.ReadToEnd();
                jsonContent = jsonContent.Substring(1, jsonContent.Length - 2);
                PM2_5 weather = jsonContent.ToClass<PM2_5>();
                return weather;
            }
            catch (Exception)
            {
                return new PM2_5() { error = "连接服务器出错！" };
            }
        }
    }
}
